package com.leige.utils.tool;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

@Component
public class JSONUtils {
	private static final Log logger = LogFactory.getLog(JSONUtils.class);
	private static ObjectMapper jacksonObjectMapper=new ObjectMapper();
	
	@Resource(name="jacksonObjectMapper")
	public void setJacksonObjectMapper(ObjectMapper jacksonObjectMapper) {
		JSONUtils.jacksonObjectMapper = jacksonObjectMapper;
	}
	
	public static String toJSONString(Object obj) {
		try {
			return	jacksonObjectMapper.writeValueAsString(obj);
		} catch (JsonProcessingException e) {
			logger.error("对象序列化为json字符串失败"  ,e);
			return null;
		}
	}

	public static File toJSONFile(Object obj,File outFile) {
		try {
			jacksonObjectMapper.writeValue(outFile, obj);
			return outFile;
		} catch (IOException e) {
			logger.error("对象序列化为文件"+outFile.getAbsolutePath()+"失败"  ,e);
			return null;
		}
	}
	
	public static void toJSONFile(Object obj,OutputStream out) {
		try {
			jacksonObjectMapper.writeValue(out, obj);
		} catch (IOException e) {
			logger.error("对象序列化至输出流失败"  ,e);
		}
	}
	
	public static <T> T fromObject(String content,Class<T> t) {
		try {
			return	jacksonObjectMapper.readValue(content, t);
		} catch (IOException e) {
			logger.error("json字符串反序列化为"+t.getName()+"类型失败"  ,e);
			return null;
		}
	}
	public static Object fromObject(String content ) {
		return fromObject(content,Object.class);
	}
	public static ArrayList<?> fromArray(String content ) {
		return fromObject(content,ArrayList.class);
	}	
	public static <T> T fromObject(File inputfile,Class<T> t) {
		try {
			return	jacksonObjectMapper.readValue(inputfile, t);
		} catch (IOException e) {
			logger.error("读文件"+inputfile.getAbsoluteFile()+"反序列化为"+t.getName()+"类型失败"  ,e);
			return null;
		}
	}
	public static Object fromObject(File inputfile ) {
		return fromObject(inputfile,Object.class);
	}
	public static ArrayList<?> fromArray(File inputfile) {
		return fromObject(inputfile,ArrayList.class);
	}
	public static <T> T fromObject(InputStream inputStream,Class<T> t) {
		try {
			return	jacksonObjectMapper.readValue(inputStream, t);
		} catch (IOException e) {
			logger.error("读文件输入域反序列化为"+t.getName()+"类型失败"  ,e);
			return null;
		}
	}
	public static Object fromObject(InputStream inputStream ) {
		return fromObject(inputStream,Object.class);
	}
	public static ArrayList<?> fromArray(InputStream inputStream) {
		return fromObject(inputStream,ArrayList.class);
	}
}
